package com.tan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tan.domain.ProvinceCityDistrict;
import com.tan.domain.User;
import com.tan.service.AsyncService;
import com.tan.service.UserService;
import com.tan.service.impl.UserServiceImpl;
import com.tan.util.EasyExcelUtil;
import com.tan.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.GraphLayout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * @author tlj
 * @date 2022/06/29 11:32:19
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AsyncService asyncService;

    @RequestMapping("/getList")
    public Object getList() {
        List<ProvinceCityDistrict> data = UserServiceImpl.provinceCityDistricts;
        log.info("获取省信息");
        System.out.println("size : " + GraphLayout.parseInstance(UserServiceImpl.provinceCityDistricts).totalSize());
        data = data.stream().filter(e -> "广西壮族自治区".equals(e.getValue())).collect(Collectors.toList());
        return data;
    }

    @RequestMapping("/getData")
    public Object getProvince() {
        System.out.println(UserServiceImpl.provinceCityDistricts.size());
        log.info("日志级别排序为： TRACE < DEBUG < INFO < WARN < ERROR -->");
        log.trace("这个是trace");
        log.debug("这个是debug");
        log.info("这个是info");
        log.warn("这个是warm");
        log.error("这个是error");
        return UserServiceImpl.provinceCityDistricts;
    }

    @RequestMapping("/easy")
    public Object easyTest(HttpServletResponse response) throws IOException, IllegalAccessException, NoSuchFieldException {

        List<User> list = userService.list();
        EasyExcelUtil.writeEasyExcel(response, User.class, list, "测试数据");
        return "ok";
    }

    /**
     * <p> MultipartFile 这个类一般是用来接收前台传过来的文件信息 </p >
     */
    @PostMapping("/importTestData")
    public Object importTestData(@RequestParam("multipartFile") MultipartFile multipartFile) throws IOException {
        if (multipartFile.isEmpty()) {
            return "参数为空";
        }
        List<User> importTestDataReqList = EasyExcelUtil.readExcel(multipartFile.getInputStream(), User.class, new EasyExcelUtil.ExcelListener<>());
        importTestDataReqList.forEach(System.out::print);
        return importTestDataReqList;
    }

    @GetMapping("/aop")
    public String aopTest(String id, String name) {
        //System.out.println("请求参数："+id+",name:"+name);
        System.out.println("this is method");
        //int a = 10 / 0;
        return "这是执行的方法的返回结果";
    }

    @GetMapping("/movies")
    public String completableFutureTask() throws ExecutionException, InterruptedException {
        //开始时间
        long start = System.currentTimeMillis();
        // 开始执行大量的异步任务
        List<String> words = Arrays.asList("F", "T", "S", "Z", "J", "C");
        CountDownLatch count = new CountDownLatch(words.size());
        List<CompletableFuture<List<String>>> completableFutureList =
                words.stream()
                        .map(word -> asyncService.completableFutureTask(word, count))
                        .collect(Collectors.toList());
        count.await();
        System.out.println("这是主线程");
        // CompletableFuture.join（）方法可以获取他们的结果并将结果连接起来
        List<List<String>> results = completableFutureList.stream().map(CompletableFuture::join).collect(Collectors.toList());
        // 打印结果以及运行程序运行花费时间
        System.out.println("Elapsed time: " + (System.currentTimeMillis() - start));
        return results.toString();
    }

    @GetMapping("/addUser")
    public void addUser() {
        long start = System.currentTimeMillis();

        for (int i = 0; i < 500; i++) {
            CompletableFuture<List<User>> userList = userService.addUserBatch();
            try {
                userService.saveBatch(userList.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

        }
        System.out.println("耗时：" + (System.currentTimeMillis() - start) / 1000 + " 秒");
    }

    @GetMapping("/getUser")
    public void get() {
        long start = System.currentTimeMillis();
       // User u = userService.getById("1851005");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "FXa4Vb5j");
        User user = userService.getOne(queryWrapper);
        int cont = userService.count();
        System.out.println(user);
        System.out.println("共" + cont + "条数据");
        System.out.println("耗时：" + (System.currentTimeMillis() - start) + " 秒");
        List<User> list = userService.list();
        list=list.stream().limit(1500L).collect(Collectors.toList());
        System.out.println(list.size());
        log.info("list 大小{}", list.size());

    }
}
